import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    changeInputValue(state, value) {
      state.inputValue = value
    },
    // 添加任务项
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.inputValue = '',
        state.nextId++
    },
    // 根据id删除对应的任务
    removeItem(state, id) {
      // 先根据id查找索引
      const index = state.list.findIndex(item => item.id === id)
      // 根据索引删除对应的元素
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    changeStatus(state, param) {
      const index = state.list.findIndex(item => item.id === param.id)
      // 根据索引删除对应的元素
      if (index !== -1) {
        state.list[index].done = param.status
      }
    },
    //清除已完成的事件
    clearDone(state) {
      // 将未完成的事件过滤出来并赋值给list
      state.list = state.list.filter(item => item.done == false)
    },
    changeViewKey(state, key) {
      state.viewKey = key
    }
  },
  actions: {
    getList(context) {
      axios.get('/list.json').then(({
        data
      }) => {
        // console.log(data);
        context.commit('initList', data)
      })
    }
  },
  getters: {
    // 计算未完成的事件条数
    unDondeLength(state) {
      return state.list.filter(item => item.done == false).length
    },
    changeItemList(state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        // 不能赋值 这样list值就发生了变化 只能过滤
        return state.list.filter(item => !item.done)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(item => item.done)
      }
      return state.list
    }
  },
  modules: {}
})
